<template>
  <div id="realName">
    <van-cell-group>
      <van-field
        custom-style="font-size: 13px;font-weight:400;"
        :value="realName"
        label="真实姓名"
        :readonly="auth_status"
        @input="realNameInput"
        placeholder="请输入真实姓名"
        required
        input-align="right"
        :disabled="fnlist.auth_status==1?true:false"
      />
      <van-field
        custom-style="font-size: 13px;font-weight:400;"
        :value="idAccount"
        label="证件号码"
        :readonly="auth_status"
        :focus="accountFocus"
        required
        type="idcard"
        @input="idAccountInput"
        placeholder="请输入证件号码"
        input-align="right"
        :disabled="fnlist.auth_status==1?true:false"
      />
      <div class="selectDataBox">
        <van-field
          custom-style="font-size: 13px;font-weight:400; z-index: 1;"
          :value="selectDate"
          required
          readonly="readonly"
          label="有效日期"
          placeholder="请选择有效日期"
          input-align="right"
          :disabled="fnlist.auth_status==1?true:false"
        />
        <div class="mask" @click="showTime"></div>
      </div>
      <template v-if="!auth_status">
        <van-field
          custom-style="font-size: 13px;font-weight:400;"
          required
          label="证件照片"
          input-align="right"
          :disabled="true"
        />
      </template>
    </van-cell-group>
    <!--上传后展示-->
    <template v-if="!auth_status">
      <div class="upImg">
        <van-uploader class="up" @afterread="headerUp1">
          <div class="img">
            <img :src="idcard_frontimg" alt v-if="idcard_frontimg" />
            <img src="https://wx.9thsurvey.com/base/images/id_face.png" alt v-else />
          </div>
        </van-uploader>
        <van-uploader class="up" @afterread="headerUp2">
          <div class="img logo">
            <img :src="idcard_backimg" alt v-if="idcard_backimg" />
            <img src="https://wx.9thsurvey.com/base/images/id_back.png" alt v-else />
          </div>
        </van-uploader>
      </div>
      <van-cell-group>
        <van-field
          custom-style="font-size: 13px;font-weight:400;"
          required
          label="人脸拍照"
          input-align="right"
          :disabled="true"
        />
      </van-cell-group>
      <!--提交按钮-->
      <div class="footer">
        <div class="footer_img">
          <img :src="tempFile" alt />
        </div>
      </div>

      <div class="footer footer-pad">
        <span>错误示例</span>
      </div>
      <div class="footer-bom">
        <div class="li">
          <img src="/static/imgs/celian2x.png" alt />
        </div>
        <div class="li">
          <img src="/static/imgs/mohu2x.png" alt />
        </div>
        <div class="li">
          <img src="/static/imgs/zhedang2x(1).png" alt />
        </div>
        <div class="li">
          <img src="/static/imgs/canque2x.png" alt />
        </div>
      </div>
      <div class="footer-bom">
        <div class="li">
          <img src="/static/imgs/celian.png" class="lib" alt />
        </div>
        <div class="li">
          <img src="/static/imgs/mohu.png" class="lib" alt />
        </div>
        <div class="li">
          <img src="/static/imgs/zhedang.png" class="lib" alt />
        </div>
        <div class="li">
          <img src="/static/imgs/canque.png" class="lib" alt />
        </div>
      </div>
      <div class="under">
        <div class="under-img" @click="chooseimage">
          <img src="/static/imgs/icon-lijirenzheng.png" alt />
        </div>
      </div>
      <div class="goin">
        <van-button
          color="linear-gradient(to right, #4bb0ff, #6149f6)"
          @click="save"
          size="small"
          block
          round
          class="goin"
        >提交</van-button>
      </div>
    </template>

    <!--有效日期弹窗-->
    <van-action-sheet :show="isShow" :round="false">
      <van-datetime-picker
        type="date"
        v-model="currentDate"
        :max-date="maxDate"
        :min-date="minDate"
        @confirm="confirm"
        @cancel="cancel"
      />
    </van-action-sheet>

    <!--提示弹窗-->
    <van-toast id="van-toast" />
    <!--证件认证成功之后弹窗-->
    <van-dialog id="van-dialog" />
  </div>
</template>

<script>
import Toast from "@/../static/vant/toast/toast";
import Dialog from "../../../static/vant/dialog/dialog";
export default {
  data() {
    return {
      realName: "",
      idAccount: "",
      isShow: false,
      selectDate: "",
      currentDate: new Date().getTime(),
      maxDate: new Date(2070, 10, 1).getTime(),
      minDate: new Date(2020, 0, 1),
      idcard_frontimg: "", // 证件照片正面i
      idcard_front: "", // 证件照片正面id
      idcard_backimg: "", // 证件照片背面
      idcard_back: "", // 证件照片背面id
      fice_pic_id: "", // 面部照片id
      tempFile: "https://wx.9thsurvey.com/base/images/id_head.png", // 面部照片
      fnlist: {},
      auth_status: 0
    };
  },
  methods: {
    //  获取用户信息
    fnInitialize() {
      this.$http
        .post({
          url: "/mobile/api/userinfo",
          data: {
            customer_id: wx.getStorageSync("userInfo").customer_id
          }
        })
        .then(res => {
          this.fnlist = res.data;
          this.auth_status = this.fnlist.auth_status;
          this.realName = this.fnlist.real_name; // 姓名
          this.idAccount = this.fnlist.id_card; // 号码
          this.selectDate = this.fnlist.validity_date; // 日期
          // 更新一下缓存
          wx.getStorage({
            key: "userInfo",
            success: res => {
              res.data.auth_status = this.auth_status;
              res.data.real_name = this.realName;
              wx.setStorageSync("userInfo", res.data);
            }
          });
          if (this.fnlist.auth_status == 1) {
            Toast("您已通过身份认证，请不要重复认证");
          }
        });
    },
    // 拍照
    chooseimage() {
      var that = this;
      wx.chooseImage({
        count: 1,
        itemList: ["从相册中选择", "拍照"],
        itemColor: "#a3a2a2",
        success(res) {
          that.tempFile = res.tempFilePaths[0];
          that.urlTobase64(res.tempFilePaths[0], 3);
        }
      });
    },
    //  头像上传1
    headerUp1(event) {
      this.idcard_frontimg = event.mp.detail.file.path;
      this.urlTobase64(event.mp.detail.file.path, 1);
    },
    //  头像上传2
    headerUp2(event) {
      this.idcard_backimg = event.mp.detail.file.path;
      this.urlTobase64(event.mp.detail.file.path, 2);
    },
    urlTobase64(url, num) {
      wx.getFileSystemManager().readFile({
        filePath: url, //选择图片返回的相对路径
        encoding: "base64", //编码格式
        success: res => {
          //成功的回调
          let base64 = "data:image/jpeg;base64," + res.data;
          this.$http
            .post({
              url: "/mobile/api/uploadfile",
              data: {
                customer_id: wx.getStorageSync("userInfo").customer_id,
                files: base64
              }
            })
            .then(res => {
              if (res.code == "RX0000") {
                if (num == 1) {
                  this.idcard_front = res.data.id;
                } else if (num == 2) {
                  this.idcard_back = res.data.id;
                } else {
                  this.fice_pic_id = res.data.id;
                }
              } else {
                wx.showToast({
                  title: res.data
                });
              }
            });
        }
      });
    },
    cancel() {
      this.isShow = false;
    },
    confirm(event) {
      this.selectDate = this.changeTime(event.mp.detail).slice(0, 10);
      this.isShow = false;
    },
    // 毫秒转换成 日期时间 格式“yyyy-MM-dd HH:MM:SS”
    changeTime(time) {
      if (time) {
        var oDate = new Date(time),
          oYear = oDate.getFullYear(),
          oMonth = oDate.getMonth() + 1,
          oDay = oDate.getDate(),
          oHour = oDate.getHours(),
          oMin = oDate.getMinutes(),
          oSen = oDate.getSeconds(),
          oTime =
            oYear +
            "-" +
            this.getBz(oMonth) +
            "-" +
            this.getBz(oDay) +
            " " +
            this.getBz(oHour) +
            ":" +
            this.getBz(oMin) +
            ":" +
            this.getBz(oSen); //拼接时间
        return oTime;
      } else {
        return "";
      }
    },
    //补0
    getBz(num) {
      if (parseInt(num) < 10) {
        num = "0" + num;
      }
      return num;
    },
    onClose() {
      this.isShow = false;
    },
    showTime() {
      if (!this.auth_status) {
        this.isShow = true;
      }
    },
    realNameInput(e) {
      this.realName = e.mp.detail;
    },
    idAccountInput(e) {
      this.idAccount = e.mp.detail;
    },
    /**
     * 身份证验证
     */
    verify_sfz(sfz) {
      if (sfz.length !== 18) return false;
      const a_i = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
      const a_last = ["1", "0", "X", "9", "8", "7", "6", "5", "4", "3", "2"];
      let sum = sfz
        .slice(0, -1)
        .split("")
        .reduce((a, n, i) => {
          return a + n * a_i[i];
        }, 0);
      return sfz.substr(-1) === a_last[sum % 11];
    },
    /**
     * 提交
     */
    save() {
      if (
        this.fnlist.real_name != null &&
        this.fnlist.id_card != null &&
        this.fnlist.validity_date != null
      ) {
        Toast("您已通过身份认证，请不要重复认证");
      } else {
        this.realName !== "" && (this.realName = this.realName.trim());
        this.idAccount !== "" && (this.idAccount = this.idAccount.trim());
        //        this.selectDate  和证件照图片
        //  校验
        if (this.realName == "") {
          Toast("请输入真实姓名");
          return;
        }
        if (this.idAccount == "") {
          Toast("请输入证件号码");
          return;
        } else {
          if (!this.verify_sfz(this.idAccount)) {
            Toast("请您输入正确的证件号码");
            return;
          }
        }
        if (this.selectDate == "") {
          Toast("请选择有效日期");
          return;
        }
        if (this.idcard_frontimg == "") {
          Toast("请选择身份证正面");
          return;
        }
        if (this.idcard_backimg == "") {
          Toast("请选择身份证背面");
          return;
        }
        if (this.tempFile == "") {
          Toast("请进行人脸拍照");
          return;
        }
        this.$http
          .post({
            url: "/mobile/api/userCardAuth",
            data: {
              real_name: this.realName, // 真实姓名
              idcard_num: this.idAccount, // 证件号码
              validity_date: this.selectDate, // 有效期至
              idcard_front_id: this.idcard_front, // 证件照片正面id
              idcard_back_id: this.idcard_back, // 证件照片背面id
              fice_pic_id: this.fice_pic_id // 手持证件照地址
            }
          })
          .then(res => {
            if (res.code == "RX0000") {
              Toast("提交成功");
              wx.navigateBack({
                delta: 1, // 返回上一级页面。
                success: () => {
                  this.fnInitialize();
                }
              });
            } else {
              if (res.msg == "调起验证服务失败，请重试") {
                Toast.fail(res.data);
              } else {
                Toast.fail(res.msg);
              }
            }
          });
      }
    }
  },
  /**
   * 初始化参数
   */
  onLoad() {
    this.fnInitialize();
    this.idcard_frontimg = "";
    this.idcard_front = "";
    this.idcard_backimg = "";
    this.idcard_back = "";
    this.fice_pic_id = "";
    this.tempFile = "https://wx.9thsurvey.com/base/images/id_head.png";
  }
};
</script>

<style lang='less' scoped>
#realName {
  .selectDataBox {
    position: relative;
    .mask {
      width: 100%;
      height: 100%;
      position: absolute;
      left: 0px;
      top: 0px;
      z-index: 2;
    }
  }
  .upImg {
    width: 100%;
    // height: 260px;
    box-sizing: border-box;
    padding: 20px;
    overflow: hidden;
    .img {
      width: 148px;
      height: 85px;
      background: #f9f9f9;
      text-align: center;
      float: left;
      & > img {
        width: 100%;
        height: 100%;
        //  vertical-align: middle;
      }
      &.logo {
        margin-left: 30px;
      }
      & > .icon {
        width: 100%;
        height: 45px;
        line-height: 45px;
      }
      & > .tip_text {
        width: 100%;
        text-align: center;
        color: #df6050;
        font-size: 12px;
      }
    }
    .up {
      .img {
        width: 148px;
        height: 85px;
        background: #f9f9f9;
        text-align: center;
        & > img {
          width: 100%;
          height: 100%;
          vertical-align: middle;
        }
        &.logo {
          margin-left: 30px;
        }
        & > .icon {
          width: 100%;
          height: 45px;
          line-height: 45px;
        }
        & > .tip_text {
          width: 100%;
          text-align: center;
          color: #df6050;
          font-size: 12px;
        }
      }
    }
  }
  .goin {
    width: 60%;
    height: 30px;
    line-height: 30px;
    margin: 10px auto;
  }
}
.footer {
  width: 100%;
  .footer_img {
    width: 157px;
    height: 105px;
    margin: 0 auto;
    img {
      width: 100%;
      height: 100%;
    }
  }
}
.footer-pad {
  margin: 14px 0;
  padding: 0 21px;
  box-sizing: border-box;
  span {
    text-align: left;
    font-size: 8px;
    font-family: PingFangSC-Medium, PingFang SC;
    font-weight: 500;
    color: rgba(5, 5, 5, 1);
    line-height: 12px;
  }
}
.footer-bom {
  width: 100%;
  padding: 0 21px;
  overflow: hidden;
  box-sizing: border-box;
  .li {
    width: 25%;
    float: left;
    text-align: center;
    img {
      width: 55px;
      height: 41px;
    }
    .lib {
      width: 18px;
      height: 21px;
    }
  }
}
.under {
  width: 100%;
  margin: 18px 0 50px 0;
  .under-img {
    width: 120px;
    height: 27px;
    margin: 0 auto;
    img {
      width: 100%;
      height: 100%;
    }
  }
}
</style>
